package core

import (
	"context"

	"github.com/astaxie/beego/logs"
	"github.com/batchcorp/rabbit"
	"github.com/streadway/amqp"
)

type RabbitOperate struct {
	Client   *rabbit.Rabbit
	callback func(msg amqp.Delivery) error // Consumer called-back
	ctx      context.Context
}

/**
 * RabbitOperate
 * callback : 用来处理消费者的回调函数
 * ctx ： 上下文管理
**/
func NewRabbitOperate(
	client *rabbit.Rabbit,
	callback func(msg amqp.Delivery) error,
	ctx context.Context,
) *RabbitOperate {
	return &RabbitOperate{
		Client:   client,
		callback: callback,
		ctx:      ctx,
	}
}

// Consumer-data
func (r *RabbitOperate) Consumer() {
	r.Client.Consume(r.ctx, nil, r.callback)
}

// Producter-data
func (r *RabbitOperate) Publish(data []byte) {

	if err := r.Client.Publish(r.ctx, r.Client.Options.QueueName, data); err != nil {
		logs.Info("Push failed: ", err)
	}
}

// Close()
func (r *RabbitOperate) Close() (err error) {
	err = r.Client.Close()
	return err
}
